package com.tanhua.sso.controller;

import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class SmsController {

    @Autowired
    private SmsService smsService;

    /**
     * 登录第一步---手机号登录
     * /user/login
     * @param param
     * @return
     */
    @PostMapping("login")
    //@RequestBody该注解用于读取 Request 请求的 body 部分数据
    public ResponseEntity<ErrorResult> sendCheckCode(@RequestBody Map<String, String> param){
        //获得前端请求过来的电话号码
        String phone = param.get("phone");
        ErrorResult errorResult = null;
        try{
            //调用sendCheckCode方法，发送验证码
            errorResult = smsService.sendCheckCode(phone);
            //返回的ErrorResult对象是null，表示发送成功
            if (null == errorResult){
                //给前端返回一个成功
                return ResponseEntity.ok(null);
            }
        }catch (Exception e){
            //出现异常，发送失败，记录日志
            log.error("发送短信验证码失败~ phone = " + phone, e);
            //设置约定的状态码和信息
            errorResult = ErrorResult.builder().errCode("000002").errMessage("短信验证码发送失败！").build();
        }
        //将状态码和约定的对象信息返回
        //status() -> 设置状态码
        //HttpStatus.INTERNAL_SERVER_ERROR -> 500
        //body() -> 设置响应体内容
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

}
